const Router = require('koa-router')
const Write = require('../models/write')

let router = new Router({ prefix: '/write' })

// 文章保存
router.post('/save', ctx => {
  let data = ctx.request.body
  let write = new Write(data)
  let success = true
  write.save(err => {
    success = !err ? true : false
  })

  if (success) {
    ctx.body = {
      status: 200,
      message: '保存成功'
    }
  } else {
    ctx.body = {
      status: -1,
      message: '保存失败'
    }
  }
})

// 文章获取
router.get('/get', async ctx => {
  let success = true
  let data = await Write.find((err, list) => {
    success = !err ? true : false
  })
  ctx.body = {
    status: success ? 200 : -1,
    message: success ? '查询成功' : '系统错误',
    data: data || []
  }
})

//文章详情
router.post('/detail', async ctx => {
  let success = true
  const id = ctx.request.body.id
  let data = await Write.find({ _id: id }, (err, d) => {
    success = !err ? true : false
  })
  // eslint-disable-next-line require-atomic-updates
  ctx.body = {
    status: success ? 200 : -1,
    message: success ? '查询成功' : '系统错误',
    data: data[0]
  }
})

router.post('/list', async ctx => {
  let limit = ctx.request.body.pageSize || 10
  let currentPage = ctx.request.body.page || 1
  let res = Write.find({})
    .skip((parseInt(currentPage) - 1) * parseInt(limit))
    .limit(parseInt(limit))

  await res.then(data => {
    ctx.body = {
      status: 200,
      message: '查询成功',
      data: data
    }
  })
})

router.delete('/delete/:id', async ctx => {
  console.log(ctx.params.id, 're')
  await Write.remove({ _id: ctx.params.id }, err => { }).then(res => {
    console.log(res, 'res')
    ctx.body = {
      status: 200,
      message: '删除成功',
      id: ctx.params.id
    }
  })
})

module.exports = router
